<template>
  <div>
    <div style="padding: 20px;display: flex;justify-content: center" id="addAd">
      <el-form
        ref="adForm"
        :model="adForm"
        label-width="100px"
        :hide-required-asterisk="true"
        class="adForm"
        label-position="left"
      >
        <el-form-item
          v-for="item,key in adForm"
          :label="$t('ad.'+key)"
          :rules="adFormRules[key]"
          v-if="key !== 'adId'"
          :prop="key"
        >
          <span slot="label">
            <i class="required" :class="{'required-hide':unrequired.includes(key)}"></i>
            {{$t('ad.'+key)}}
          </span>

          <el-select
            v-if="selectOptions.hasOwnProperty(key)"
            v-model="adForm[key]"
            :filterable="key ==='productId'"
            @change="selectOptionChange(key)"
            :filter-method="filterMethod(key)"
          >
            <el-option
              v-for="option in selectOptions[key]"
              :key="option.value"
              :label="$t('option.'+option.label).indexOf('.')>-1?option.label:$t('option.'+option.label)"
              :value="option.value"
            ></el-option>
          </el-select>
          <editor ref="editor" v-else-if="key === 'productDetails'" :code.sync="adForm[key]"></editor>
          <div v-else-if="key === 'packages'">
            <div v-for="pg,pgIndex in item" class="packageItem">
              <span>{{$t('ad.packageName')}}</span>
              <el-input v-model="pg.packageName" class="margin-left"></el-input>
              <span class="margin-left">
                <el-button @click="addProduct(pgIndex)">{{$t('ad.addProduct')}}</el-button>
                <el-button @click="delPackage(pgIndex)" class="margin-left">{{$t('ad.delPackages')}}</el-button>
              </span>
              <div class="productTh">
                <div>{{$t('ad.productName')}}</div>
                <div calss="half">{{$t('ad.productid')}}</div>
                <div calss="130">{{$t('ad.count')}}</div>
                <div>{{$t('ad.attr')}}</div>
              </div>
              <div v-for="product,index in pg.packageDetail" style="margin-bottom: 10px">
                <el-select
                  v-model="product.productId"
                  @change="selectProduct(pgIndex,index,true)"
                  :filterable="true"
                >
                  <el-option
                    v-for="option in selectOptions['productId']"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>

                <el-input class="margin-left" disabled v-model="product.productId" />
                <el-input-number
                  v-model="product.count"
                  class="margin-left"
                  controls-position="right"
                  :min="1"
                  :max="1000"
                  :label="$t('common.productNumber')"
                />
                  <div v-if="product.attr" style="display: inline-block;">
                <el-tooltip
                  effect="dark"
                  placement="top"
                  v-if="product.attr"
                     v-for="(item, idx) in JSON.parse(product.attr)"
                    :key="idx"
                  :content="`${item.attrValue.join(',')}`"
                >
                  <div class="attr" style="width: 30px;">{{item.attrName}}</div>
                </el-tooltip>
                  </div>

                <el-button
                  @click="selectProductAttr(pgIndex,index)"
                  class="margin-left"
                >{{$t('ad.enSelectAttr')}}</el-button>
                <el-button
                  @click="delPackageProduct(pgIndex,index)"
                  class="margin-left"
                >{{$t('ad.delProduct')}}</el-button>
              </div>

              <div style="margin-bottom: 10px">
                <span>{{$t('ad.price')}}</span>
                <el-input
                  :placeholder="$t('common.price')"
                  class="margin-left"
                  type="number"
                  v-model="pg.price"
                ></el-input>
                <el-input
                  :placeholder="$t('common.currency')"
                  class="margin-left"
                  style="width: 80px"
                  v-model="pg.currency"
                ></el-input>
              </div>
            </div>
            <el-button style="margin-top: 10px" @click="addPackages">{{$t('ad.addPackages')}}</el-button>
            <el-button style="margin-top: 10px" @click="syncAttr">{{$t('ad.syncAttr')}}</el-button>
          </div>
          <uploadImg v-else-if="key==='adImg'" :upload-list="uploadList"></uploadImg>
          <el-input
            v-else
            v-model="adForm[key]"
            :type="key ==='productAttr'?'textarea':numberInput.includes(key)?'number':'text'"
          ></el-input>
          <el-input
            v-if="key === 'price'"
            :placeholder="$t('common.currency')"
            style="width: 80px"
            v-model="adOtherData.currency"
          ></el-input>
          <el-dialog
            :title="$t('common.attr')"
            :visible.sync="productAttrVisible"
            width="800px"
            center
          >
            <div v-if="cloneProductSelectAttr" v-for="(attr, a) in cloneProductSelectAttr">
              <span>{{attr.attrName}}</span>
              <el-checkbox-group v-model="tList" @change="changeSelectAttr">
                <el-checkbox
                  :label="`${attr.attrName}_${b}`"
                  v-for="(value, b) in attr.attrValue"
                >{{value}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-dialog>
        </el-form-item>
        <div id="saveFlag"></div>
        <el-button
          id="saveButton"
          type="primary"
          @click="confirmEdit"
          style="width: 100%;"
        >{{$t('common.save')}}</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import axios from "axios";
import editor from "../components/editor/editor";
import uploadImg from "../components/uploadImg";
import { currency } from "../../config";

export default {
  name: "productAddAdvertising",
  components: {
    editor,
    uploadImg
  },
  data() {
    let validatecurrency = (rule, value, callback) => {
      if (this.adOtherData.currency === "") {
        callback(new Error(this.$t("ad.currencyTip")));
      } else {
        callback();
      }
    };
    let validatproductDetails = (rule, value, callback) => {
      if (this.adForm.productDetails === "") {
        callback(new Error(this.$t("ad.productDetailsTip")));
      } else {
        callback();
      }
    };
    return {
      tList: [],
      pacakageAttr: {},
      adForm: {
        adId: "",
        productId: "",
        countryId: "62",
        adName: "",
        adImg: "",
        // mouldId: '',
        price: "",
        orig: "",
        maxNum: "",
        packages: [],
        domain: "",
        url: "",
        fbId: "",
        cloak: "",
        productDetails: ""
      },
      adOtherData: {
        currency: "",
        attr: ""
      },
      adFormRules: {
        productId: [
          {
            required: true,
            message: this.$t("common.selectProduct"),
            trigger: "blur"
          }
        ],
        adName: [
          {
            required: true,
            message: this.$t("common.adNameTip"),
            trigger: "blur"
          }
        ],
        productDetails: [{ validator: validatproductDetails, trigger: "blur" }],
        domain: [
          {
            required: true,
            message: this.$t("common.selectDomain"),
            trigger: "blur"
          }
        ],
        countryId: [
          {
            required: true,
            message: this.$t("product.countryIdSelectTip"),
            trigger: "blur"
          }
        ],
        fbId: [{ required: true, message: "fbid", trigger: "blur" }],
        price: [
          {
            required: true,
            message: this.$t("common.priceTip"),
            trigger: "blur"
          },
          { validator: validatecurrency, trigger: "blur" }
        ]
      },
      productOptions: [],
      domainOptions: [],
      productAttrVisible: false,
      productSelectAttr: {},
      cloneProductSelectAttr: {},
      pgIndex: 0,
      index: 0,
      uploadList: [],
      numberInput: ["price", "orig", "maxNum"],
      unrequired: ["url", "orig", "cloak", "maxNum"]
    };
  },
  computed: {
    ...mapState(["countryOptions"]),

    selectOptions() {
      return {
        productId: this.productOptions,
        countryId: this.countryOptions,
        domain: this.domainOptions
      };
    }
  },
  methods: {
    ...mapMutations(["delOpenPage"]),
    filterMethod(key) {
      let method = {};

      return method[key];
    },
    getProductOptions() {
      let params = {
        pageSize: 99999,
        currentPage: 1
      };
      this.$productList(params).then(response => {
        if (response.data) {
          this.productOptions = [];
          response.data.forEach(v => {
            let option = {
              value: v.productId,
              label: v.productName
            };
            this.productOptions.push(option);
          });
        }
      });
    },
    getDomains() {
      this.$domains({}).then(response => {
        if (response && response.code === "success") {
          this.domainOptions = [];
          response.data.forEach(v => {
            let option = {
              value: v,
              label: v
            };
            this.domainOptions.push(option);
          });
        }
      });
    },
    addPackages() {
      let pg = {
        packageName: "",
        price: "",
        currency: this.adOtherData.currency || "",
        packageDetail: [{ productId: "", count: 0, attr: "", orgAttr: "" }]
      };
      this.adForm.packages.push(pg);
    },
    selectProductAttr(pgIndex, index) {
      this.productAttrVisible = true;
      this.selectProduct(pgIndex, index);
    },
    selectProduct(pgIndex, index, sync) {
      console.log(this.tList)
      this.pgIndex = pgIndex;
      this.index = index;
      let params = {
        pageSize: 1,
        currentPage: 1,
        id: this.adForm.packages[pgIndex].packageDetail[index].productId
      };
      this.$productList(params).then(response => {
        if (response.code === "success") {
          let attr = response.data[0].productAttr;
          this.adForm.packages[pgIndex].packageDetail[
            index
          ].orgAttr = this.formatAttr(attr);
          if (sync) {
            this.adForm.packages[pgIndex].packageDetail[
              index
            ].attr = this.formatAttr(attr);

            const attData = JSON.parse(attr);
            this.tList = [];
            attData.forEach((a) => {
              a.attrValue.forEach((b, idx) => this.tList.push(`${a.attrName}_${idx}`))
            })
          } else {
            this.adForm.packages[pgIndex].packageDetail[index].attr = this
              .adForm.packages[pgIndex].packageDetail[index].attr
              ? this.adForm.packages[pgIndex].packageDetail[index].attr
              : this.formatAttr(attr);
            this.productSelectAttr = this.adForm.packages[pgIndex]
              .packageDetail[index].attr
              ? this.formatAttr1(
                  this.adForm.packages[pgIndex].packageDetail[index].attr
                )
              : attr
              ? JSON.parse(attr)
              : attr;
          }
          console.log(JSON.parse(attr));
          this.cloneProductSelectAttr = attr ? JSON.parse(attr) : attr;
          console.log('ffffff',this.adForm);
        }
      });
    },
    saveProductAttr() {
      let params = {
        pageSize: 1,
        currentPage: 1,
        id: this.adForm.productId
      };
      this.$productList(params).then(response => {
        if (response.code === "success") {
          this.adOtherData.attr = response.data[0].productAttr
            ? JSON.parse(response.data[0].productAttr)
            : response.data[0].productAttr;
        }
      });
    },
    changeSelectAttr() {
      console.log(this.cloneProductSelectAttr);
      let list = [];
      this.tList.forEach(item => {
        let arr = item.split("_"),
          attrName = arr[0],
          attrIdx = arr[1];
        let temp = {};
        this.cloneProductSelectAttr.forEach(b => {
          if (b.attrName === attrName) {
            temp = {
              productId: b.productId,
              countryId: b.countryId,
              attrName,
              url: b.url[attrIdx],
              attrValue: b.attrValue[attrIdx]
            };
          }
        });
        list.push(temp);
      });
      console.log(list);
      const attrData = this.formatlAttrData(list);
      this.adForm.packages[this.pgIndex].packageDetail[
        this.index
      ].attr = JSON.stringify(attrData);
    },
    formatlAttrData(data) {
      let attrList = [],
        uniqueObj = {};
      data.forEach(a => {
        let tempObj = {
          countryId: a.countryId,
          productId: a.productId || 0,
          attrName: a.attrName,
          attrValue: [],
          url: []
        };
        data.forEach(b => {
          console.log(!uniqueObj[a.attrName]);
          if (!uniqueObj[a.attrName] && a.attrName === b.attrName) {
            tempObj.attrValue.push(b.attrValue);
            tempObj.url.push(b.url);
          }
        });
        if (tempObj.attrValue.length > 0 && tempObj.url.length > 0)
          attrList.push(tempObj);
        uniqueObj[a.attrName] = 1;
      });
      console.log(attrList);
      return attrList;
    },
    formatAttr(attr) {
      if (!attr.trim()) {
        return;
      }
      // let data = JSON.parse(attr);
      // let after = "";
      // for (let [k, v] of Object.entries(data)) {
      //   if (v.length > 0) {
      //     after = after + k + ":" + v.sort().join(",") + "\n";
      //   }
      // }
      return attr;
    },
    formatAttr1(attr) {
      let data = attr;
      let row = [];
      let attrs = {};
      row = data.split("\n");

      for (let i = 0; i < row.length - 1; i++) {
        attrs[row[i].split(/[:：]/)[0]] = row[i]
          .split(/[:：]/)[1]
          .split(/[,，]+/);
      }
      return attrs;
    },
    selectOptionChange(key) {
      if (key === "productId") {
        return this.saveProductAttr();
      } else if (key === "countryId") {
        return (() => {
          this.adOtherData.currency = currency[this.adForm.countryId] || "";
        })();
      }
    },
    addProduct(pgIndex) {
      let product = { productId: "", count: 0, attr: "", orgAttr: "" };
      this.adForm.packages[pgIndex].packageDetail.push(product);
    },
    delPackage(pgIndex) {
      this.adForm.packages.splice(pgIndex, 1);
    },
    delPackageProduct(pgIndex, index) {
      if (this.adForm.packages[pgIndex].packageDetail.length > 1) {
        this.adForm.packages[pgIndex].packageDetail.splice(index, 1);
      }
    },
    confirmEdit() {
      if (!this.editCheck("adForm")) return;
      let params = {};
      Object.assign(params, this.adForm, this.adOtherData);
      if (!params.adId) delete params.adId;
      let params1 = Object.assign({}, params);
      delete params1.productDetails;
      delete params1.attr;
      delete params1.orig;
      params1.packages = JSON.stringify(params1.packages);
      this.$addAdvertises([params1]).then(response => {
        if (response.code && response.code === "success") {
          params.adId
            ? this.$message.success(this.$t("common.editSuccess"))
            : this.$message.success(this.$t("common.addSuccess"));
          params.productDetails = this.formatProductDetails(
            params.productDetails
          );
          this.qiniuUpload(
            this.createFile(JSON.stringify(params)),
            response.data.id + ".txt"
          );
          if (this.$route.query.copy) {
            this.delOpenPage(this.$route.path);
            this.$router.push("/productAdvertising");
          }
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    formatProductDetails(str) {
      let handle = [
        {
          reg: new RegExp(
            `(?<=(<img.*?)(_src=".+?")(.*?))( src=".+?")(?=(.+?>))`,
            "g"
          ),
          type: "img",
          replace: ""
        },
        {
          reg: new RegExp(
            `(?<=(<img.*?))( src=".+?")(?=(.*?_src=".+?".+?>))`,
            "g"
          ),
          type: "img",
          replace: ""
        },
        {
          reg: new RegExp(`(?<=(<img.*?))( src)(=".*?")(?=(.*?>))`, "g"),
          type: "img",
          replace: "_src" + "$3"
        },
        {
          reg: new RegExp(`(?<=(<img.*?))(_src)(=".*?")(?=(.*?>))`, "g"),
          type: "img",
          replace:
            ' src="http://gl.svip51.com/common/image/spinner.gif"' +
            " _src" +
            "$3"
        },
        {
          reg: /(text-indent:.*?;)/g,
          replace: ""
        }
      ];
      handle.forEach(v => {
        if (v.type !== "img") {
          str = str.replace(v.reg, v.replace);
        }
      });
      if (str) {
        str.match(/(<img.*?)(src=".+?")(.*?>)/g) &&
          str.match(/(<img.*?)(src=".+?")(.*?>)/g).forEach(iStr => {
            str = str.replace(iStr, function(item) {
              handle.forEach(v => {
                if (v.type === "img") {
                  item = item.replace(v.reg, v.replace);
                }
              });
              return item;
            });
          });
      }
      return str;
    },
    editCheck(ref) {
      let valid = true;
      this.$refs[ref].validate(v => {
        valid = v;
      });
      return valid;
    },

    qiniuUpload(file, name, path) {
      let filename = (path || "cod/content/" + this.adForm.domain + "/") + name,
        getTokenUrl = this.getTokenUrl,
        uploadUrl = this.uploadUrl;

      axios
        .post(
          getTokenUrl,
          { key: filename },
          {
            transformRequest: [
              function(data) {
                let ret = "";
                for (let it in data) {
                  ret +=
                    encodeURIComponent(it) +
                    "=" +
                    encodeURIComponent(data[it]) +
                    "&";
                }
                return ret;
              }
            ],
            headers: {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          }
        )
        .then(res => {
          if (res && res.token) {
            let formData = new FormData();
            formData.append("key", filename);
            formData.append("token", res.token);
            formData.append("file", file);

            axios.post(uploadUrl, formData);
          }
        });
    },
    init() {
      this.getProductOptions();
      this.getDomains();
      this.observerSave();
      this.$refs.adForm.clearValidate();
      if (this.$route.query.id) {
        let domain = this.$route.query.domain;
        let url = this.qiniuDownLoadUrl + "cod/content/" + domain + "/";
        this.getFileByUrl(url + this.$route.query.id + ".txt").then(
          response => {
            if (response) {
              let data = response;
              for (let [k, v] of Object.entries(data)) {
                if (this.adForm.hasOwnProperty(k)) {
                  this.adForm[k] = v;
                }
                if (this.adOtherData.hasOwnProperty(k)) {
                  this.adOtherData[k] = v;
                }
              }
              if (this.$route.query.copy) {
                this.adForm.adId = "";
              } else {
                this.adForm.adId = this.$route.query.id;
              }
              this.uploadList = [
                {
                  url: data.adImg,
                  name: data.adImg && data.adImg.replace(/(.*\/)/, ""),
                  status: 1,
                  percentage: 100
                }
              ];
              this.$refs.editor[0].initCode(data.productDetails);
            }
          }
        );
      } else {
        this.resetData();
      }
    },
    resetData() {
      for (let key of Object.keys(this.adForm)) {
        if (key === "packages") {
          this.adForm[key] = [];
        } else {
          this.adForm[key] = "";
        }
      }
      for (let key of Object.keys(this.adOtherData)) {
        this.adOtherData[key] = "";
      }
      this.uploadList = [];
      this.$refs.editor[0].initCode("");
    },
    syncAttr() {
      for (let pgIndex in this.adForm.packages) {
        for (let index in this.adForm.packages[pgIndex].packageDetail) {
          this.selectProduct(pgIndex, index, true);
        }
      }
      this.saveProductAttr();
    },
    observerSave() {
      let observerConfig = {
        root: null,
        rootMargin: "0px",
        threshold: [0]
      };
      let observer = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
          if (entry.intersectionRatio > 0) {
            document.querySelector("#saveButton").style.position = "unset";
            document.querySelector("#saveButton").style["max-width"] = "unset";
            document.querySelector("#saveButton").style["bottom"] = "unset";
          } else {
            let width = document.querySelector("#saveButton").offsetWidth;
            document.querySelector("#saveButton").style.position = "fixed";
            document.querySelector("#saveButton").style["max-width"] =
              width + "px";
            document.querySelector("#saveButton").style["z-index"] = 1000;
            document.querySelector("#saveButton").style["bottom"] = "10px";
          }
        });
      }, observerConfig);
      observer.observe(document.querySelector("#saveFlag"));

      let edui_body = false,
        edui_tool = false;
      let observer1 = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
          if (entry.intersectionRatio > 0) {
            if (entry.target.id) {
              edui_body = true;
            } else {
              edui_tool = true;
            }
          } else {
            if (entry.target.id) {
              edui_body = false;
            } else {
              edui_tool = false;
            }
          }

          if (edui_body && !edui_tool) {
            if (document.querySelector(".edui-toolbar")) {
              let width = document.querySelector(".edui-toolbar").offsetWidth;
              document.querySelector(".edui-toolbar").style.position = "fixed";
              document.querySelector(".edui-toolbar").style.top = 0;
              document.querySelector(".edui-toolbar").style["z-index"] = 1000;
              document.querySelector(".edui-toolbar").style["width"] =
                width + "px";
            }
          } else {
            if (document.querySelector(".edui-toolbar")) {
              document.querySelector(".edui-toolbar").style.position = "unset";
              document.querySelector(".edui-toolbar").style.top = "unset";
              document.querySelector(".edui-toolbar").style["z-index"] =
                "unset";
              document.querySelector(".edui-toolbar").style["width"] = "unset";
            }
          }
        });
      }, observerConfig);
      observer1.observe(document.querySelector("[for=productDetails]"));

      let observeBody = () => {
        if (document.querySelector("#editor")) {
          observer1.observe(document.querySelector("#editor"));
        } else {
          setTimeout(() => {
            observeBody();
          }, 100);
        }
      };

      observeBody();
    }
  },
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  beforeCreate() {
    this.$store.commit("saveAdEditId", this.$route.query.id);
    this.$store.commit("saveSaveDomain", this.$route.query.domain);
  },
  watch: {
    uploadList: {
      handler(newV, oldV) {
        if (!newV || !newV.length) {
          return;
        }
        this.adForm.adImg =
          newV.filter(v => {
            return v && v.url !== "";
          })[0] &&
          newV.filter(v => {
            return v && v.url !== "";
          })[0].url;
      },
      deep: true
    }
  }
};
</script>

<style lang="less">
#addAd .el-input {
  width: 200px;
  .el-input-number {
  }
}
#addAd .el-input-number .el-input {
  width: 130px;
}
.margin-left {
  margin-left: 20px;
}
.productTh {
  div {
    display: inline-block;
    margin-right: 20px;
    width: 200px;
  }
}
.adForm {
  border: 2px outset #999999;
  border-radius: 4px;
  padding: 20px;
}
.attr {
  display: inline-block;
  width: 200px;
  text-align: center;
  white-space: nowrap;
  word-break: break-all;
  text-overflow: ellipsis;
  overflow: hidden;
  vertical-align: bottom;
  margin: 0 20px;
}
.packageItem {
  border: 1px dashed #aaa;
  border-radius: 4px;
  padding: 10px 10px 0;
  margin: 10px 0 0;
  background-color: #fff9f2;
}
.edui-editor-body img {
  max-width: 100%;
}
</style>